<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Str;

class SnakeCaseRequestParams
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 转换请求参数为蛇形形式
        $this->convertRequestData($request);

        return $next($request);
    }

    /**
     * Convert request data from camelCase to snake_case.
     *
     * @param \Illuminate\Http\Request $request
     * @return void
     */
    protected function convertRequestData($request)
    {
        $data = $request->all();

        $convertedData = $this->convertArrayKeys($data);

        $request->replace($convertedData);
    }

    /**
     * Recursively convert array keys from camelCase to snake_case.
     *
     * @param array $array
     * @return array
     */
    protected function convertArrayKeys($array)
    {
        $convertedArray = [];

        foreach ($array as $key => $value) {
            $convertedKey = Str::snake($key);

            if (is_array($value)) {
                $convertedArray[$convertedKey] = $this->convertArrayKeys($value);
            } else {
                $convertedArray[$convertedKey] = $value;
            }
        }

        return $convertedArray;
    }
}
